<?php

namespace app\system\controller\finance;

use app\common\controller\System;
use app\system\controller\goods\ZipArchive;
use ba\Filesystem;
use hehe\Numeral;
use hehe\Str;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use think\facade\Db;

/**
 * 商品管理
 */
class Commission extends System {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = [];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\finance\Commission();
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            if(empty($data['dk_time'])) $this->error(__('请选择打款时间'));

            $update = [
                'dk_time' => strtotime($data['dk_time'])
            ];

//            print_r($data);die;


            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($update);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    public function cancel(){
        $params = $this->request->param();
        db::name('customer_order_agent')->where(['id' => $params['id']])->update(['dk_time' => null, 'dk_status' => 0]);
        $this->success();
    }


    public function dk(){
        $params = $this->request->param();
        $update = [
            'dk_status' => 1,
            'dk_time' => empty($params['dk_time']) ? null : strtotime($params['dk_time'])
        ];
        db::name('customer_order_agent')->where(['id' => $params['id']])->update($update);
        $this->success();
    }

    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();

        $field = "o.id, a.id agent_id, o.out_trade_no, o.create_time, a.profit, ag.name, a.commission_ratio, a.commission, a.commission_rate, a.commission_tax, a.to_commission, a.dk_status, a.dk_time";

        $res = $this->model->alias('o')
            ->join('customer_order_agent a', 'o.id=a.order_id')
            ->join('agent ag', 'a.agent_id=ag.id')
            ->where(['o.filter_id' => $this->filter['id']])
            ->field($field);

        $param = $this->request->param();

        if(!empty($param['year'])){
            $res->whereYear('create_time', $param['year']);
        }
        if(!empty($param['month'])){
            if(empty($param['year'])) $this->error(__('请选择年份'));
            $month = $param['month'] < 10 ? '0' . $param['month'] : $param['month'];
            $res->whereMonth('create_time', $param['year'] . '-' . $month);
        }
        if(!empty($param['type'])){
            $res->where(['type' => $param['type']]);
        }
        if(isset($param['dk_status']) && $param['dk_status'] !== null && $param['dk_status'] !== ''){
            if($param['dk_status'] == 0){
                $res->whereNull('dk_time');
            }else{
                $res->whereNotNull('dk_time');
            }
        }

        $res = $res->order($order)->paginate($limit);

        $list = $res->items();


        foreach($list as $key => $val){
            $list[$key]['profit'] = empty($val['profit']) ? 0 : Numeral::numberFormat($val['profit'] / 100);
            $list[$key]['commission'] = empty($val['commission']) ? 0 : Numeral::numberFormat($val['commission'] / 100);
            $list[$key]['to_commission'] = empty($val['to_commission']) ? 0 : Numeral::numberFormat($val['to_commission'] / 100);
//            $list[$key]['dk_status'] = empty($val['dk_time']) ? 0 : 1;
            $list[$key]['dk_time'] = empty($val['dk_time']) ? null : date('Y-m-d', $val['dk_time']);
            $list[$key]['create_time'] = empty($val['create_time']) ? null : date('Y-m-d', $val['create_time']);
        }



        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }




}